package icu.luoxi.controller;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author Cao Jiwen
 * @version V1.0
 */
@RestController
@RequestMapping("/file")
public class FilesController {

    @ApiOperation(value = "文件上传")
    @PostMapping("/uploads")
    public ResponseEntity<List<String>> uploadFiles(@RequestParam("files") MultipartFile[] files) throws FileNotFoundException {
        List<String> fileUrls = new ArrayList<>();
        for (MultipartFile file : files) {
            //获取绝对路径
            String path = ResourceUtils.getURL("classpath:").getPath()+"static/upload";
            String parent = path.replace('/', '\\').substring(1,path.length());
            //创建当前的目录
            File dir = new File(parent);
            if (!dir.exists()){
                dir.mkdirs();
            }
            //获取文件名
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //使用UUID生成文件名
            String fileName = UUID.randomUUID().toString()+suffix;
            File dest = new File(dir,fileName);
            try {
                file.transferTo(dest);
                fileUrls.add(fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new ResponseEntity<>(fileUrls, HttpStatus.OK);
    }

    @ApiOperation(value = "文件下载")
    @GetMapping("download")
    public ResponseEntity<ByteArrayResource> download(@RequestParam String fileName) throws IOException {
        //读取文件
        try {
            String basePath = ResourceUtils.getURL("classpath:").getPath()+"static/upload";
            String parent = basePath.replace('/', '\\').substring(1,basePath.length());
            // 读取文件内容为字节数组
            Path path = Paths.get(parent +"\\"+ fileName);
            byte[] fileBytes = Files.readAllBytes(path);
            // 创建字节数组资源
            ByteArrayResource resource = new ByteArrayResource(fileBytes);
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
            // 返回响应实体
            return ResponseEntity.ok().headers(headers).contentLength(fileBytes.length).contentType(MediaType.APPLICATION_OCTET_STREAM).body(resource);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
